package com.hm.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hm.base.auto.su.BeanUtil;
import com.hm.base.domain.ReqLog;
import com.hm.base.mapper.ReqLogMapper;
import com.hm.base.vo.ReqLogVo;
import com.hm.common.def.DataStatusDef;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.PageInfo;
import com.hm.common.su.bean.PageInfo.PageParam;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;
import com.hm.common.util.StringUtil;

/**
 * @author shishun.wang
 * @date 下午3:17:48 2017年8月21日
 * @version 1.0
 * @describe
 */
@Service
public class ReqLogServiceImpl implements ReqLogService {

	@Autowired
	private ReqLogMapper reqLogMapper;

	@Override
	public void addReqLog(ReqLogVo reqLogVo) {
		if (CommonUtil.isAnyEmpty(reqLogVo.getReqName(), reqLogVo.getReqSource(), reqLogVo.getCreateUser())) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		ReqLog reqLog = new ReqLog();
		{
			BeanUtil.copyProperties(reqLogVo, reqLog);
			reqLog.setId(null);
			reqLog.setCreateTime(new Date());
			reqLog.setStatus(DataStatusDef.ENABLE.name());
		}

		reqLogMapper.insert(reqLog);
	}

	@Override
	public ReqLogVo getReqLog(Long reqLogId) {
		if (CommonUtil.isEmpty(reqLogId)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		ReqLog reqLog = reqLogMapper.selectByPrimaryKey(reqLogId);
		if (CommonUtil.isEmpty(reqLog)) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		ReqLogVo vo = new ReqLogVo();
		BeanUtil.copyProperties(reqLog, vo);
		vo.setCreateTime(DateUtil.data2long(reqLog.getCreateTime()));

		return vo;
	}

	@Override
	public PageInfo<ReqLogVo> query(PageParam pageParam, String reqName, Long createUser, Long startCreateTime,
			Long endCreateTime) {
		Page<ReqLog> page = PageHelper.startPage(pageParam.getPage(), pageParam.getSize(), true);

		Map<String, Object> params = new HashMap<String, Object>();
		if (StringUtil.isNotBlank(reqName)) {
			params.put("reqName", reqName);
		}
		if (CommonUtil.isEmpty(createUser)) {
			params.put("createUser", createUser);
		}

		if (!CommonUtil.isAnyEmpty(startCreateTime, endCreateTime)) {
			params.put("startCreateTime", startCreateTime);
			params.put("endCreateTime", endCreateTime);
		}

		reqLogMapper.query(params);
		List<ReqLogVo> vos = new ArrayList<ReqLogVo>();
		page.getResult().forEach(item -> {
			ReqLogVo vo = new ReqLogVo();
			BeanUtil.copyProperties(item, vo);
			vo.setCreateTime(DateUtil.data2long(item.getCreateTime()));

			vos.add(vo);
		});

		return new PageInfo<ReqLogVo>(vos, page.getPages(), page.getTotal());
	}

}
